const router = require('koa-router')();
const DB = require('../../module/db.js');
const tools = require('../../module/tools.js');
const multer = require('koa-multer');



// 配置图片上传目录
const storage = multer.diskStorage({
	destination: function(req, file, cb){
		cb(null, 'static/upload')
	},
	filename: function(req, file, cb){
		let fileFormat = (file.originalname).split('.');

		// 需要处理上传的文件命名（这里要填上后缀，不然koa-multer会丢失后缀名）
		cb(null, file.fieldname + '-' + Date.now() + '.' + fileFormat[fileFormat.length - 1]);

		//cb(null, file.fieldname + '-' + Date.now())
	}
});
const upload = multer({storage: storage});
// const upload = multer({dest: 'upload/'});



router.get('/', async (ctx) => {
	
	
	let pageindex = (ctx.query.page) ? parseInt(ctx.query.page, 0) : 1;
	let pageSize = (ctx.query.size) ? parseInt(ctx.query.size, 0) : 10;
	let result = await DB.findOne('link', {}, {
		index: pageindex,
		size: pageSize
	});
	
	let countNum = await DB.count('article', {});
	
    await ctx.render('admin/link/list', {
    	list: result,
    	pageIndex: pageindex,
    	totalPages: Math.ceil(countNum / pageSize),
    });
});



router.get('/add', async (ctx) => {

    await ctx.render('admin/link/add');
});

router.post('/add', upload.single('pic'), async (ctx) => {

	let title = ctx.req.body.title;
	let pic = ctx.req.file ? ctx.req.file.path.replace('static\\', "") : ''; // 返回文件名
	let url = ctx.req.body.url;
	let sort = ctx.req.body.sort;
	let status = ctx.req.body.status;
	
	let addResult = await DB.insertOne('link', {
        title,
        pic,
        url,
        sort,
        status,
        add_time: new Date(),
    });
    
    ctx.redirect(ctx.state.__HOST__ + '/admin/link');
});



router.get('/edit', async (ctx) => {

    let id = ctx.query.id;
    let result = await DB.findOne('link', {
        _id: DB.getObjectID(id)
    });

    await ctx.render('admin/link/edit', {
        list: result[0],
        referer: ctx.state.G.referer
    });
});

router.post('/edit', upload.single('pic'), async (ctx) => {

    let id = ctx.req.body.id;
    let pic = ctx.req.file ? ctx.req.file.path.replace('static\\', '') : ''; // 返回文件名
    let referer = ctx.req.body.referer || '';
    
    let json = {
    	title: ctx.req.body.title.trim(),
    	url: ctx.req.body.url.trim(),
    	sort: ctx.req.body.sort.trim()
    }
    
    if(pic) {
    	json['pic'] = pic;
    }


    let addResult = await DB.updateOne('link', {
    	_id: DB.getObjectID(id)
	}, json);

    (referer) ? ctx.redirect(referer) : ctx.redirect(ctx.state.__HOST__ + '/admin/link');
});


router.get('/delete', async (ctx) => {

    ctx.body = '删除用户';
});

module.exports = router.routes();